package erfgame.frontend.desktop.view.terrain.iso.handler;

import java.awt.event.MouseEvent;
import java.util.List;

import erfgame.core.graphics.renderer.chain.RendererChain;
import erfgame.core.world.terrain.insertion.SurfaceInsertion;

import erfgame.frontend.desktop.view.terrain.iso.EntitySelection;
import erfgame.frontend.desktop.view.terrain.iso.IsometricTerrainView;

public class MouseOverInteractionHandler extends BaseInteractionHandler {

	private IsometricTerrainView view;
	private EntitySelection selection;
	
	public MouseOverInteractionHandler( IsometricTerrainView view, EntitySelection selection ) {
		this.view = view;
		this.selection = selection;
	}
	
	@Override
	public MouseEvent[] handleMouseEvent(MouseEvent e) {
		if( e.getID() == MouseEvent.MOUSE_MOVED || e.getID() == MouseEvent.MOUSE_DRAGGED ) {
			List<SurfaceInsertion> insertions;
			insertions = view.getInsertionsAt(e.getX(), e.getY());
			if( insertions != null && insertions.size() > 0 ) {
				boolean found = false;
				for( int i=0; i<insertions.size(); i++ ) {
					SurfaceInsertion insertion;
					insertion = insertions.get(i);
					RendererChain rendererChain;
					rendererChain = insertion.getRendererChain();
					if( rendererChain.getHead().getEntity() != null ) {
						if( !selection.getSelected().contains(rendererChain) ) {
							selection.clear();
							selection.addRendererChain(rendererChain, view.getCurrentRotation());
							// repaint?
							view.repaint();
						}
					} else {
						// TODO it's a grid tile highlight all 
						// byte blockGridId = ((SurfaceTerrainImageInsertion)insertion).getSurfaceImage().getBlockGridId();
						if( !selection.getSelected().contains(rendererChain) ) {
							selection.clear();
							selection.addRendererChain(rendererChain, view.getCurrentRotation());
							// repaint?
							view.repaint();
						}
					}
					found = true;
					break;
						
				}
				if( !found ) {
					if( selection.getSelected().size() > 0 ) {
						 selection.clear();
						 // repaint?
						 view.repaint();
					}
				}
			} else {
				selection.clear();
			}
		}
		return super.handleMouseEvent(e);
	}
}
